import store from '@/store';
import { setShowLocalToken } from '@/store/slice/global';
import { saveMessageInfo } from '@/store/slice/message';
import axios from 'axios';

import { getToken } from './auth';

const errMsg = (msg: string) => {
  store.dispatch(saveMessageInfo({ type: 'error', content: msg }));
};

// 创建axios实例
const service = axios.create({
  timeout: 5000,
});

// request interceptor request拦截器
service.interceptors.request.use(
  (config) => {
    config.headers['Accept'] = 'application/json';
    const token = getToken();
    if (token && token !== 'undefined') {
      config.headers['Authorization'] = token;
    }
    return config;
  },
  (error) => {
    Promise.reject(error);
  },
);

// response interceptor request拦截器
service.interceptors.response.use(
  function (response) {
    const res = response.data;

    if (res?.retCode !== 0 && res?.errCode !== 0) {
      errMsg(res?.retMsg || res?.errMsg || '服务端发生错误！');
    }

    return res;
  },
  function (error) {
    // 本地无权限时，弹窗提示输入token
    if (error.response?.status === 401 && window.location.hostname === 'localhost') {
      store.dispatch(setShowLocalToken(true));
      return Promise.resolve({});
    }

    if (error.message.includes('timeout')) {
      errMsg('网络超时，请重试~');
      return Promise.reject(error);
    }
    if (error.message) {
      return Promise.reject(error);
    }
    return Promise.reject(error);
  },
);

export default service;

/**
 * GET形式的调用
 * @param url 接口地址
 * @param data 参数
 * @param options 放置headers等数据
 * @returns
 */
export const _get = (url: string, data?: any, options?: any): Promise<any> => {
  return service.get(url, {
    ...options,
    params: {
      ...data,
    },
  });
};

/**
 * POST形式的调用
 * @param url 接口地址，支持老版 pb名_接口名 的形式
 * @param data 参数
 * @param options 放置headers等数据
 * @returns
 */
export const _post = (url: string, data?: any, options?: any): Promise<any> => {
  return service.post(url, data, options);
};
